package com.kucai.yifaqapp.ui.fragment;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kucai.yifaqapp.R;
import com.kucai.yifaqapp.global.HttpAdress;
import com.kucai.yifaqapp.global.Info;
import com.kucai.yifaqapp.model.CustomObserver;
import com.kucai.yifaqapp.model.network.HttpJsonUtils;
import com.kucai.yifaqapp.model.network.entity.res.WebSocketMsgBean;
import com.kucai.yifaqapp.model.network.entity.res.uploadPicBean;
import com.kucai.yifaqapp.model.network.entity.res.uploadPicBena;
import com.kucai.yifaqapp.model.network.entity.res.websocktdizhiBena;
import com.kucai.yifaqapp.util.websocket.WebSocketUtils2;
import com.kucai.yifaqapp.widget.BaseLoadingDialog;
import com.kucai.yifaqapp.widget.BaseLoadingDialogChat;
import com.kucai.yifaqapp.widget.KeyBordStateUtil;
import com.kucai.yifaqapp.widget.changeNikeDiolog;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 计划交流
 */
public class z_planFragment extends BaseFragmentSimple {
    private String websocketUrl;
    private RecyclerView recyclewviewlist;
    private String port;
    private List<WebSocketMsgBean> mdatas = new ArrayList<>();
    private List<WebSocketMsgBean> mdatas1 = new ArrayList<>();
    private Gson mgosn = new Gson();
    private z_palnFragmentAdapter adapter;
    private boolean ismovetoposition = false;//默认是滚动的
    private MyLinnerlayout manager;
    private TextView gonggao;
    private String note;
    private EditText enterdata;
    private Button fasong;
    private Button fasongpic;
    private RelativeLayout reletivecontent;
    //    private WebSocketUtils utils;
    private RelativeLayout right1;  //滚动
    private RelativeLayout right2;  //清楚
    private RelativeLayout right3;  //昵称
    private RelativeLayout right4;  //头像
    private ImageView right1img;
    private TextView right1text;
    private boolean isconnected = false;
    private BaseLoadingDialogChat dialog2;
    private RelativeLayout enterspace;

    private Switch saidan; //晒单
    private Switch pingbi;  //屏蔽他人投注
    private Switch pingbijihua;//屏蔽计划
    private boolean issaidan = false;
    private boolean ispingbi = false;
    private boolean ispingbijihua = false;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    private int upload = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.z_planfragment, container, false);
        initView(v);
        initEvents();
        initKeYboardlistener();
        return v;
    }

    private void initKeYboardlistener() {

    }

    private void initEvents() {
        //发送文字
        fasong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (enterdata.getText().toString().isEmpty()) {

                } else {
                    try {
                        //先加密韦url  再base64加密
                        String text1 = java.net.URLEncoder.encode(enterdata.getText().toString(), "utf-8");
                        String encodeWord = Base64.encodeToString(text1.getBytes("utf-8"), Base64.DEFAULT);
                        WebSocketUtils2.getInstance().sendMsg(encodeWord);
                        enterdata.setText("");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        //发送图片
        fasongpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("android.intent.action.GET_CONTENT");
                intent.setType("image/*");
                startActivityForResult(intent, 999);//打开系统相册
                upload = 999;//这是发送图片
            }
        });
        //锁屏
        right1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ismovetoposition = !ismovetoposition;
                if (ismovetoposition) {
                    right1img.setImageResource(R.mipmap.chat_ungundong);
                    right1text.setText("锁屏");
                } else {
                    right1img.setImageResource(R.mipmap.chat_gundong);
                    right1text.setText("滚屏");
                }
            }
        });
        //清屏
        right2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mdatas.clear();
                adapter.notifyDataSetChanged();
            }
        });
        //修改昵称
        right3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //修改昵称
                Intent intent = new Intent(getActivity(), changeNikeDiolog.class);
                startActivity(intent);
            }
        });
        //修改头像
        right4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("android.intent.action.GET_CONTENT");
                intent.setType("image/*");
                startActivityForResult(intent, 999);//打开系统相册
                upload = 888;//这是修改头像
            }
        });

        //晒单
        saidan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    issaidan = true;
                } else {
                    issaidan = false;
                }
            }
        });
        //屏蔽他人投注
        pingbi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ispingbi = true;
                } else {
                    ispingbi = false;
                }
            }
        });
        //屏蔽计划
        pingbijihua.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ispingbijihua = true;
                    //当选择时候  我们开始屏蔽计划任务的
                    for (int i = 0; i < mdatas.size(); i++) {
                        if (mdatas.get(i).level.equals("98")) {
                            mdatas1.add(mdatas.get(i));
                        }
                    }
                    mdatas.removeAll(mdatas1);
                    adapter.notifyDataSetChanged();
                } else {
                    ispingbijihua = false;
                }
            }
        });
        KeyBordStateUtil keyBordStateUtil = new KeyBordStateUtil(getActivity());
        keyBordStateUtil.addOnKeyBordStateListener(mOnKeyBordStateListener);


    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    private KeyBordStateUtil.onKeyBordStateListener mOnKeyBordStateListener = new KeyBordStateUtil.onKeyBordStateListener() {

        @Override
        public void onSoftKeyBoardShow(int keyboardHeight) {
            //dp转px
            // 获得转换后的px值
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    dip2px(getActivity(), 90f));
            params.setMargins(0, 0, 0, 0);
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            enterspace.setLayoutParams(params);
//            RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
//                    LinearLayout.LayoutParams.MATCH_PARENT);
//            params1.setMargins(0, 0, 0, keyboardHeight + dip2px(getActivity(), 110f));
//            params1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
//            recyclewviewlist.setLayoutParams(params1);
            //移动到最后一个position
            if (mdatas.size() > 2) {
                MoveToPosition(manager, recyclewviewlist, mdatas.size() - 1);
            }
        }

        @Override
        public void onSoftKeyBoardHide() {
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    dip2px(getActivity(), 90f));
            params.setMargins(0, 0, 0, 0);
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            enterspace.setLayoutParams(params);
//            RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
//                    LinearLayout.LayoutParams.MATCH_PARENT);
//            params1.setMargins(0, 0, 0, dip2px(getActivity(), 110f));
//            params1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
//            recyclewviewlist.setLayoutParams(params1);
        }
    };

    private void initView(View v) {
        recyclewviewlist = v.findViewById(R.id.mlist);
        gonggao = v.findViewById(R.id.gonggao);
        enterdata = v.findViewById(R.id.enterdata);
        reletivecontent = v.findViewById(R.id.reletivecontent);
        fasong = v.findViewById(R.id.fasong);
        fasongpic = v.findViewById(R.id.fasongpic);
        right1 = v.findViewById(R.id.right1);
        right2 = v.findViewById(R.id.right2);
        right3 = v.findViewById(R.id.right3);
        right4 = v.findViewById(R.id.right4);
        saidan = v.findViewById(R.id.saidan);
        pingbi = v.findViewById(R.id.pingbi);
        pingbijihua = v.findViewById(R.id.pingbijihua);
        enterspace = v.findViewById(R.id.enterspace);
        right1img = v.findViewById(R.id.right1img);
        right1text = v.findViewById(R.id.right1text);
        manager = new MyLinnerlayout(getContext());
        recyclewviewlist.setLayoutManager(manager);
        adapter = new z_palnFragmentAdapter(getActivity(), mdatas);
        recyclewviewlist.setAdapter(adapter);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (!isconnected) {
                try {
                    dialog2 = new BaseLoadingDialogChat(getContext(), R.style.CustomDialog);
                    get_websocket_adress();
                } catch (Exception e) {

                }
            }
        }
    }

    private void get_websocket_adress() {
        //获取websocket地址和端口
        HttpJsonUtils.getHttpApiInstance()
                .get_websocket_adress(HttpAdress.getuseAdress() + "api/chat/url", Info.user.token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<websocktdizhiBena>(this) {
                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {

                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {
                        Toast.makeText(getActivity(), "请检查网络连接", Toast.LENGTH_SHORT).show();
                        if (dialog2 != null && dialog2.isShowing()) {
                            dialog2.dismiss();
                        }
                    }

                    @Override
                    protected void onCustomNext(websocktdizhiBena resCode) {
                        try {
                            //连接websocket，并且处理推送过来的消息
                            websocketUrl = resCode.getChatUrl();
                            port = resCode.getChatPort();
                            String mUrl = websocketUrl + ":" + port + "/" + Info.user.token;
                            WebSocketUtils2.getInstance().initWebsocket(mUrl, new WebSocketUtils2.MsgHandle() {
                                @Override
                                public void open() {
                                    isconnected = true;
                                }

                                @Override
                                public void getMsg(String msg) {
                                    //必须try-catch不然会导致websocket异常关闭
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            WebSocketMsgBean bean = mgosn.fromJson(msg, WebSocketMsgBean.class);
                                            if (bean.status == 2 || bean.status == 4 || bean.status == 8 || bean.status == 9) {
                                                try {
                                                    String string = new String(Base64.decode((((String) bean.msg)).getBytes(), Base64.DEFAULT));
                                                    String text2 = java.net.URLDecoder.decode(string, "utf-8");
                                                    if (text2.contains("img=")) {
                                                        if (bean.status == 2) {
                                                            bean.status = 22;
                                                        }
                                                        if (bean.status == 4) {
                                                            bean.status = 44;
                                                        }
                                                    }
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                                if (!bean.level.equals("98")) {
                                                    mdatas.add(bean);
                                                } else {
                                                    if (!ispingbijihua) {
                                                        mdatas.add(bean);
                                                    }
                                                }

                                            } else if (bean.status == 6) {
                                                //公告
                                                try {
                                                    note = "" + bean.msg;
                                                    gonggao.setText(note + "                 " + note + "                 " + note);
                                                    gonggao.setSelected(true);
                                                } catch (Exception e) {

                                                }
                                            } else if (bean.status == 1) {
                                                //别人进入聊天室
                                                TextView textView = new TextView(getActivity());
                                                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                                                        70);
                                                params.setMargins(20, 150, 20, 0);
                                                textView.setLayoutParams(params);
                                                textView.setText("  " + bean.fd + "：进入了聊天室  ");
                                                textView.setTextColor(Color.parseColor("#ffffff"));
                                                textView.setGravity(Gravity.CENTER);
                                                ObjectAnimator valueAnimator = ObjectAnimator.ofFloat(textView, "translationX", 1200);
                                                valueAnimator.setDuration(3000);
                                                valueAnimator.start();
                                                textView.setBackgroundResource(R.drawable.comeinmember);
                                                reletivecontent.addView(textView);
                                                valueAnimator.addListener(new Animator.AnimatorListener() {
                                                    @Override
                                                    public void onAnimationStart(Animator animation) {

                                                    }

                                                    @Override
                                                    public void onAnimationEnd(Animator animation) {
                                                        reletivecontent.removeView(textView);
                                                    }

                                                    @Override
                                                    public void onAnimationCancel(Animator animation) {

                                                    }

                                                    @Override
                                                    public void onAnimationRepeat(Animator animation) {

                                                    }
                                                });
                                            } else if (bean.status == 5) {
                                                enterdata.setText(String.valueOf(bean.msg) + "");
                                                fasong.setClickable(false);
                                                fasongpic.setClickable(false);
                                                enterdata.setEnabled(false);
                                                //已被禁言
                                            } else if (bean.status == 13) {
                                                //禁止发言过快
                                                enterdata.setText("请不要太快发言");
                                            } else if (bean.status == 7) {
                                                //限制发言//0能发言 1不能发言
                                                if (bean.anS.equals("1")) {
                                                    enterdata.setText("平台暂无发言权限");
                                                    fasong.setClickable(false);
                                                    fasongpic.setClickable(false);
                                                    enterdata.setEnabled(false);
                                                }
                                                if (bean.nS.equals("1")) {
                                                    enterdata.setText("前两天充值不少于" + resCode.getRech() + "元；打码量不少于" + resCode.getBet() + "元");
                                                    fasong.setClickable(false);
                                                    fasongpic.setClickable(false);
                                                    enterdata.setEnabled(false);
                                                } else {
                                                    fasong.setClickable(true);
                                                    fasongpic.setClickable(true);
                                                    enterdata.setEnabled(true);
                                                }
                                            } else if (bean.status == 10) {
                                                for (int i = 0; i < mdatas.size(); i++) {
                                                    if (mdatas.get(i).msg.equals(bean.msg)) {
                                                        mdatas.remove(i);
                                                        if (ismovetoposition) {
                                                            //不动
                                                        } else {
                                                            if (mdatas.size() != 0) {
                                                                MoveToPosition(manager, recyclewviewlist, mdatas.size() - 1);
                                                            }
                                                        }
                                                    }
                                                }
                                            } else if (bean.status == 3) {
                                                Toast.makeText(getActivity(), "登录失效，请重新登录", Toast.LENGTH_SHORT).show();
                                            } else if (bean.status == 15) {
                                                //跟单
                                                String string1 = new String(Base64.decode(((String) bean.msg).getBytes(), Base64.DEFAULT));
                                                if (!ispingbi) {
                                                    mdatas.add(bean);
                                                }
                                            }
                                            if (mdatas.size() == 0) {

                                            } else {
//                                                adapter.notifyItemInserted(mdatas.size() - 1);
                                                adapter.notifyDataSetChanged();
                                                if (dialog2 != null && dialog2.isShowing()) {
                                                    dialog2.dismiss();
                                                }
                                            }
                                            if (ismovetoposition) {
                                                //不动
                                            } else {
                                                if (mdatas.size() > 2) {
                                                    MoveToPosition(manager, recyclewviewlist, mdatas.size() - 1);
                                                }
                                            }
                                        }
                                    });
                                }

                                @Override
                                public void onClosed() {
                                    if (dialog2 != null && dialog2.isShowing()) {
                                        dialog2.dismiss();
                                    }
                                    isconnected = false;
                                }

                                @Override
                                public void onFailure() {
                                    if (dialog2 != null && dialog2.isShowing()) {
                                        dialog2.dismiss();
                                    }
                                    isconnected = false;
                                }

                                @Override
                                public void onBeginconnect() {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                if (dialog2 == null) {
                                                    dialog2 = new BaseLoadingDialogChat(getContext(), R.style.CustomDialog);
                                                    if (!dialog2.isShowing()) {
                                                        dialog2.show();
                                                    }
                                                } else {
                                                    if (!dialog2.isShowing()) {
                                                        dialog2.show();
                                                    }
                                                }
                                            } catch (Exception e) {

                                            }
                                        }
                                    });
                                }
                            });
                        } catch (Exception e) {

                        }
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //这里主动断开连接
        WebSocketUtils2.getInstance().ondestoryWebsocket();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    //发送图片
    //选择图片的回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 999 && resultCode == getActivity().RESULT_OK && null != data) {
            if (Build.VERSION.SDK_INT >= 19) {
                handleImageOnKitkat(data);
            } else {
                handleImageBeforeKitkat(data);
            }
        }
    }

    @TargetApi(19)
    private void handleImageOnKitkat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(getActivity(), uri)) {
            //如果是document类型的uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content:" +
                        "//downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果是content类型的uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            //如果是File类型的uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        displayImage(imagePath);//根据图片路径显示图片
    }

    private void handleImageBeforeKitkat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过uri和selection来获取真实的图片路径
        Cursor cursor = getActivity().getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    //首先压缩图片
    public void displayImage(String path) {
        dialog = new BaseLoadingDialog(getActivity(), R.style.custom_dialog2);
        dialog.show();
        Bitmap bitmap = BitmapFactory.decodeFile(path);
//        //开始上传
        File file = new File(path);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Luban.with(getActivity())
                        .load(file)
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                            }

                            @Override
                            public void onSuccess(File file) {
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                //读取图片到ByteArrayOutputStream
                                bitmap.compress(Bitmap.CompressFormat.PNG, 50, baos); //参数如果为100那么就不压缩
                                byte[] bytes = baos.toByteArray();
                                String strbm = Base64.encodeToString(bytes, Base64.DEFAULT);
                                if (upload == 888) {
                                    //上传头像
                                    post_requst_paly_1(strbm);
                                } else if (upload == 999) {
                                    post_requst_paly(strbm);
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                dialog.dismiss();
                            }
                        }).launch();
            }
        }).start();
    }

    Gson gson = new Gson();
    private BaseLoadingDialog dialog;

    //开始上传图片
    public void post_requst_paly(String strs) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
        uploadPicBean bean = new uploadPicBean();
        bean.picture = "data:image/png;base64," + strs;
        bean.token = Info.user.token;
        String json = gson.toJson(bean);
        Log.e("xdh", "开始上传图片");
        long starttime = System.currentTimeMillis();
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , json);
        final Request request = new Request.Builder()
                .url(HttpAdress.getuseAdress() + "api/mobile/upimgtxt")//请求的url
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                dialog.dismiss();
                Log.e("xdh", e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                uploadPicBena bena1 = gson.fromJson(response.body().string(), uploadPicBena.class);
                long stoptime = System.currentTimeMillis();
                Log.e("xdh", "上传图片成功" + (stoptime - starttime));
                if (bena1.isStatus()) {
                    //上传图片成功，需要再发普通消息，将我们的Url广播出去
                    String text1 = java.net.URLEncoder.encode("img=" + bena1.getUrl() + "&data=", "utf-8");
                    String encodeWord = Base64.encodeToString(text1.getBytes("utf-8"), Base64.NO_WRAP);
                    WebSocketUtils2.getInstance().sendMsg(encodeWord);
                }
                dialog.dismiss();
            }
        });
    }

    //开始上传图片
    public void post_requst_paly_1(String strs) {
        Log.e("xdh", "开始上传头像");
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
        uploadPicBean bean = new uploadPicBean();
        bean.picture = "data:image/png;base64," + strs;
        Log.e("xdh", strs);
        bean.token = Info.user.token;
        String json = gson.toJson(bean);
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , json);
        final Request request = new Request.Builder()
                .url(HttpAdress.getuseAdress() + "api/mobile/upimg")//请求的url
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("xdh", "---------------" + response.body().string());
                dialog.dismiss();
            }
        });
    }

    /**
     * RecyclerView 移动到当前位置，
     */
    public static void MoveToPosition(LinearLayoutManager manager, RecyclerView mRecyclerView, int n) {
        int firstItem = manager.findFirstVisibleItemPosition();
        int lastItem = manager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRecyclerView.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = mRecyclerView.getChildAt(n - firstItem).getTop();
            mRecyclerView.scrollBy(0, top);
        } else {
            mRecyclerView.scrollToPosition(n);
        }
    }

    @Override
    protected void ChangeSkin() {

    }

    @Override
    protected int setContentView() {
        return R.layout.z_planfragment;
    }

    //解决notifyinsert的bug
    public class MyLinnerlayout extends LinearLayoutManager {
        public MyLinnerlayout(Context context) {
            super(context);
        }

        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            try {
                super.onLayoutChildren(recycler, state);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    }
}
